<style lang="less">
@import "../../styles/common.less";
</style>

<template>
  <div>
    <div v-show="show">
      <Row type="flex" justify="space-between">
        <Row></Row>
        <Row>
          <Button type="primary" icon="ios-cog-outline" @click="handleConfigAuth">功能配置</Button>
          <Button type="primary" icon="ios-plus-outline" @click="handleAddMeeting">新建会议</Button>
        </Row>
      </Row>
      <Table
        class="margin-top-10"
        ref="customTable"
        :columns="meetingColumn"
        :data="meetingDataList"
        :loading="meetingLoading"
      ></Table>
      <Row type="flex" justify="end" class="margin-top-10">
        <Page
          :total="totalMeeting"
          :current="currentPage"
          :page-size="pageSize"
          @on-change="getMeeting"
          show-total
        >显示第{{currentIndex + 1}}-{{currentIndex + pageSize}}条，总数为{{totalMeeting}}条</Page>
      </Row>
    </div>
    <div v-show="!show">
      <card>
        <p slot="title">会议功能配置</p>
        <p v-show="!initialized" class="margin-bottom-10 margin-left-20">
          <span style="color:red">*</span>当前未配置会议权限，配置前会议功能不可用。
        </p>
        <div class="margin-top-20">
          <Form
            ref="authFrom"
            :model="auth"
            label-position="left"
            :label-width="100"
            :rules="authRules"
          >
            <Form-item label="密钥 key" prop="recong_host">
              <Input v-model.trim="auth.appKey" placeholder="appKey" :maxlength="32"/>
            </Form-item>
            <Form-item label="密钥 secret" prop="recong_host">
              <Input v-model.trim="auth.appSecret" placeholder="appSecret" :maxlength="32"/>
            </Form-item>
          </Form>
          <Row class="margin-top-20">
            <Button v-show="initialized" type="primary" @click="handleCancel">取消</Button>
            <Button type="primary" @click="handleSave">提交</Button>
          </Row>
        </div>
      </card>
    </div>
    <AddMeetingModal ref="addMeeting" @updated="onMeetingUpdate"/>
    <CreateInviteModal ref="createInvite" @updated="onInviteUpdate"/>
  </div>
</template>

<script>
import Utils from "@/libs/util";
import ME from "@/controllers/meeting";
import DateUtils from "../../../node_modules/iview/src/utils/date";
import iconEdit from "../../images/edit.png";
import iconPwd from "../../images/password.png";
import iconStop from "../../images/stop.png";
import iconRestart from "../../images/restart.png";
import iconDelete from "../../images/delete.png";
import iconInvite from "../../images/attendanceRecord.png";
import iconMembers from "../../images/feature.png";

import AddMeetingModal from "./components/AddMeetingModal";
import CreateInviteModal from "./components/CreateInviteModal";

import Tooltip from "../../../node_modules/iview/src/components/tooltip/tooltip";
import Btn from "../../../node_modules/iview/src/components/button/button";
import Constant from "../../libs/constants";

export default {
  components: {
    AddMeetingModal,
    CreateInviteModal,
    Tooltip,
    Btn
  },
  data() {
    return {
      show: true,
      meetingDataList: [],
      meetingLoading: true,
      initialized: false,
      pageSize: Constant.PAGE_SIZE,
      currentPage: 1,
      totalMeeting: 0,
      auth: {
        appKey: "",
        appSecret: ""
      },
      authRules: {
        app_key: [{ required: true, message: "请检查", trigger: "change" }],
        app_secret: [{ required: true, message: "请检查", trigger: "change" }]
      },
      meetingColumn: [
        {
          title: "会议图标",
          align: "center",
          width: "10%",
          key: "meet_logo",
          render: (h, { row, column, index }) => {
            //拼装url
            let imgSrc = "";
            let encode = row[column.key];
            if (encode) {
              imgSrc = encode;
              return (
                <div>
                  <img class="user-avatar" alt="图标" src={imgSrc} />
                </div>
              );
            }
            return <div />;
          }
        },
        {
          title: "状态",
          align: "center",
          key: "state"
        },
        {
          title: "会议名称",
          align: "center",
          key: "meet_name"
        },
        {
          title: "人数上限",
          align: "center",
          key: "user_limit"
        },
        {
          title: "开始时间",
          align: "center",
          width: "150px",
          key: "date_start"
        },
        {
          title: "结束时间",
          align: "center",
          width: "150px",
          key: "date_end"
        },
        {
          title: "签到截止时间",
          align: "center",
          width: "150px",
          key: "report_end"
        },
        {
          title: "邀请函",
          align: "center",
          render: (h, { row, column, index }) => {
            if (row.invites && row.invites.length > 0) {
              return h(
                "a",
                {
                  on: {
                    click: () => {
                      this.handleInvite(row);
                    }
                  }
                },
                "邀请函"
              );
            } else {
              return <div />;
            }
          }
        },
        {
          title: "操作",
          align: "center",
          width: "220px",
          render: (h, { row, column, index }) => {
            return (
              <div class="operation">
                <Tooltip content="编辑" placement="bottom">
                  <Btn
                    style={{ background: `url( ${iconEdit})` }}
                    onClick={() => this.handleEditMeeting(row)}
                  />
                </Tooltip>
                <Tooltip content="人员" placement="bottom">
                  <Btn
                    style={{ background: `url( ${iconMembers})` }}
                    onClick={() => this.handleParticipant(row)}
                  />
                </Tooltip>
                <Tooltip content="邀请函" placement="bottom">
                  <Btn
                    style={{ background: `url( ${iconInvite})` }}
                    onClick={() => this.handleInvite(row)}
                  />
                </Tooltip>
                <Tooltip content="删除" placement="bottom">
                  <Btn
                    style={{ background: `url( ${iconDelete})` }}
                    onClick={() => this.handleDelMeeting(row)}
                  />
                </Tooltip>
              </div>
            );
          }
        }
      ]
    };
  },
  async created() {
    try {
      await this.loadMeetingConfig();
      if (this.initialized) this.loadMeetings();
    } catch (error) {
      console.error(error);
      this.show = false;
    }
  },
  computed: {
    currentIndex: function() {
      return (this.currentPage - 1) * this.pageSize;
    }
  },
  methods: {
    getMeeting(page) {
      this.currentPage = page;
      this.loadMeetings();
    },
    handleQuery() {
      this.loadMeetings();
    },
    handleAddMeeting() {
      this.$refs["addMeeting"].showAsAdd();
    },
    async loadMeetingConfig() {
      let res = await ME.get_meeting_config();
      let auth = res.data;
      if (auth.appKey && auth.appSecret) {
        this.show = true;
        this.auth.appKey = auth.appKey;
        this.auth.appSecret = auth.appSecret;
        if (this.auth.appKey) {
          this.initialized = true;
        }
      }
    },
    async loadMeetings() {
      this.meetingLoading = true;
      ME.query(this.currentPage, this.pageSize)
        .then(res => {
          console.log(res);
          if (res.code !== 0) {
            //非正常就返回空表
            return;
          }
          let data = res.data;
          //检测数据块存在及长度
          if (data === undefined) {
            return;
          }
          this.meetingLoading = false;
          this.totalMeeting = data.total;
          this.formatMeetings(data.result);
        })
        .catch(error => {
          console.error(error);
          this.$Message.error("加载失败!");
        });
    },
    formatMeetings(meetings) {
      let list = [];
      meetings.map(meeting => {
        list.push(meeting);
      });
      this.meetingDataList = list;
    },
    onMeetingUpdate(meeting) {
      if (!meeting.edit_flag) {
        this.$refs["createInvite"].showAsAdd(meeting.meet);
      }
      this.loadMeetings();
    },
    onInviteUpdate() {
      this.loadMeetings();
    },
    handleDelMeeting(row) {
      this.$Modal.confirm({
        title: "确认",
        content: "删除会议【" + row.meet_name + "】？",
        onOk: () => {
          // 删除基本信息
          ME.delete(row._id).then(res => {
            if (res.code === 0) {
              this.$Message.success("删除成功!");
              this.loadMeetings();
            }
          });
        }
      });
    },
    handleParticipant(row) {
      this.$router.push({
        name: "participant",
        params: { meet_id: row._id }
      });
    },
    handleInvite(row) {
      this.$refs["createInvite"].showAsUpdate(row);
    },
    handleEditMeeting(row) {
      this.$refs["addMeeting"].showAsUpdate(row);
    },
    async handleSave() {
      let val = this.$refs["authFrom"].validate();
      if (!val) return;
      this.initialized = true;
      ME.set_meeting_config(this.auth)
        .then(() => {
          this.show = true;
          this.$Message.success("提交成功!");
        })
        .catch(() => {
          this.$Message.error("提交失败!");
        });
    },
    handleCancel() {
      this.show = true;
    },
    handleConfigAuth() {
      this.show = false;
    }
  }
};
</script>